import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
import table from './table'
import demo from './demo'
import _ from 'lodash'
const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'login',
        meta: {
            auth: false
        },
        component: () => import('@/views/login')
    },
    {
        path: '/layout',
        name: 'layout',
        meta: {
            auth: true
        },
        component: () => import('@/views/layout/index'),
        children: [
            {
                path: '/index',
                name: 'index',
                component: () => import('@/views/home')
            },
            ...demo,
            ...table
        ]
    },
    {
        path: '*',
        component: () => import('@/views/error/404')
    }
]

Vue.use(VueRouter)
const router = new VueRouter({
    routes
})

// 进度条
router.beforeEach((to, from, next) => {
    NProgress.start()
    if (to.matched.some(record => record.meta.auth)) {
        const accessToken = localStorage.getItem('accessToken')
        if (_.isEmpty(accessToken)) {
            next({
                path: '/login',
                query: {
                    redirect: to.fullPath
                }
            })
        } else {
            if (to.path === '/login') {
                next({ path: '/index' })
            } else {
                next()
            }
        }
    } else {
        next()
    }
    NProgress.done()
})

router.afterEach(() => {
    NProgress.done()
})

export default router
